package problem224;

import java.util.Stack;

//224.基本计算器
//https://leetcode.cn/problems/basic-calculator/

class Solution {
    public int calculate(String _s) {
        char[] s = _s.toCharArray();
        int n = s.length;
        Stack<Integer> stack = new Stack<>();
        int i = 0;

        int sum = 0;
        int sign = 1;
        while(i < n) {
            if(s[i] == ' ') {
                i++;
            }else if(s[i] == '-') {
                sign = -1;
                i++;
            }else if(s[i] == '+') {
                sign = 1;
                i++;
            }else if(s[i] == '(') {
                stack.push(sum);
                stack.push(sign);
                sum = 0;
                sign = 1;
                i++;
            }else if(s[i] == ')') {
                int preSign = stack.pop();
                int preSum = stack.pop();
                sum = (preSum + sum * preSign);
                i++;
            }else { //数字
                int j = i;
                while(i+1 < n && s[i+1] >= '0' && s[i+1] <= '9') {
                    i++;
                }
                int val = Integer.valueOf(_s.substring(j, i+1));
                sum += val * sign;
                i++;
            }
        }
        return sum;
    }
}